import { SQL, sql } from 'drizzle-orm';

export interface PaginationParams {
  pageNum: number;
  pageSize: number;
}

export interface SearchParams {
  [key: string]: any;
}

/**
 * 分页工具类
 */
export class PaginationUtil {
  /**
   * 标准化分页参数
   */
  static normalizePagination(params: any): PaginationParams {
    const pageNum = Math.max(1, Number(params.pageNum) || 1);
    const pageSize = Math.min(100, Math.max(1, Number(params.pageSize) || 10));
    
    return { pageNum, pageSize };
  }

  /**
   * 构建模糊查询条件
   */
  static buildLikeConditions(table: any, searchFields: string[], searchParams: SearchParams): SQL[] {
    const conditions: SQL[] = [];
    
    searchFields.forEach(field => {
      const value = searchParams[field];
      if (value && typeof value === 'string' && value.trim()) {
        conditions.push(sql`${table[field]} like ${`%${value.trim()}%`}`);
      }
    });
    
    return conditions;
  }

  /**
   * 构建精确匹配条件
   */
  static buildEqualConditions(table: any, exactFields: string[], searchParams: SearchParams): SQL[] {
    const conditions: SQL[] = [];
    
    exactFields.forEach(field => {
      const value = searchParams[field];
      if (value !== undefined && value !== null && value !== '') {
        if (typeof value === 'string' && !isNaN(Number(value))) {
          conditions.push(sql`${table[field]} = ${Number(value)}`);
        } else {
          conditions.push(sql`${table[field]} = ${value}`);
        }
      }
    });
    
    return conditions;
  }

  /**
   * 构建枚举条件
   */
  static buildEnumConditions(table: any, enumFields: string[], searchParams: SearchParams): SQL[] {
    const conditions: SQL[] = [];
    
    enumFields.forEach(field => {
      const value = searchParams[field];
      if (value !== undefined && ['0', '1'].includes(String(value))) {
        conditions.push(sql`${table[field]} = ${String(value)}`);
      }
    });
    
    return conditions;
  }

  /**
   * 构建排序条件
   */
  static buildOrderBy(table: any, sortField?: string, sortOrder: 'asc' | 'desc' = 'asc'): any {
    const defaultSort = table.userId || table.id || table.createTime;
    const sortBy = sortField && table[sortField] ? table[sortField] : defaultSort;
    
    return sortOrder === 'desc' ? sql`${sortBy} desc` : sql`${sortBy} asc`;
  }

  /**
   * 计算偏移量
   */
  static calculateOffset(pageNum: number, pageSize: number): number {
    return Math.max(0, (pageNum - 1) * pageSize);
  }

  /**
   * 计算总页数
   */
  static calculateTotalPages(total: number, pageSize: number): number {
    return Math.max(1, Math.ceil(total / pageSize));
  }

  /**
   * 验证并清理查询参数
   */
  static sanitizeSearchParams(params: SearchParams, allowedFields: string[]): SearchParams {
    const sanitized: SearchParams = {};
    
    allowedFields.forEach(field => {
      const value = params[field];
      if (value !== undefined && value !== null && value !== '') {
        sanitized[field] = value;
      }
    });
    
    return sanitized;
  }
}